package de.home.filter;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class RequestAnalyser implements Filter {

   private static final Logger LOG = LogManager.getLogger(RequestAnalyser.class);

   @Override
   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
         throws IOException, ServletException {

      HttpServletRequest request = (HttpServletRequest) servletRequest;
      HttpServletResponse response = (HttpServletResponse) servletResponse;
      LOG.debug("");
      LOG.debug("[Request] ------------------------------------------------------------------");
      LOG.debug("IP : " + request.getRemoteAddr());
      LOG.debug("Method : " + request.getMethod());
      LOG.debug("Target : " + request.getServletPath());
      LOG.trace("Target : " + request.getRequestURL());
      LOG.debug("");
      Map<String, String[]> parameterMap = request.getParameterMap();
      if ( parameterMap.isEmpty() ) {
         LOG.debug("No Parameter.");
      } else {
         for (Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            for (String param : entry.getValue()) {
               LOG.debug("[Parameter] '" + key + "' : '" + param + "'");
            }
         }
      }
      // LOG.debug("----------------------------------------------------------------------------");
      LOG.debug("");
      long start = System.currentTimeMillis();

      chain.doFilter(request, response);
      LOG.debug("");
      LOG.debug("Request took {} ms.", System.currentTimeMillis() - start);
      LOG.debug("----------------------------------------------------------------------------");
   }

   @Override
   public void init(FilterConfig fConfig) throws ServletException {
   }

   @Override
   public void destroy() {
      // TODO Auto-generated method stub

   }

}
